import pygame
import sys
import time
import random

# 初始化pygame
pygame.init()

# 定义颜色
white = (255, 255, 255)
green = (0, 255, 0)
red = (213, 50, 80)
black = (0, 0, 0)

# 设置窗口大小
dis_width = 800
dis_height = 600

# 创建游戏窗口
dis = pygame.display.set_mode((dis_width, dis_height))
pygame.display.set_caption('Snake Game')

# 设置游戏时钟
clock = pygame.time.Clock()

# 字体
font = pygame.font.SysFont("Arial", 18)

# 蛇块大小
snake_block = 10

# 创建蛇的初始位置
snake_pos = [[100, 50], [90, 50], [80, 50]]

# 蛇的方向
snake_dir = 'RIGHT'

# 食物位置
food_pos = [random.randrange(1, (dis_width // 10)) * 10,
            random.randrange(1, (dis_height // 10)) * 10]

# 游戏分数
score = 0


def game_over():
    my_font = pygame.font.SysFont('times new roman', 50)
    game_over_surface = my_font.render('Game Over', True, red)
    game_over_rect = game_over_surface.get_rect()
    game_over_rect.midtop = (dis_width / 2, dis_height / 4)
    dis.blit(game_over_surface, game_over_rect)
    pygame.display.flip()
    pygame.time.wait(2000)
    pygame.quit()
    sys.exit()


def snake(snake_block, snake_list):
    snake_pos.pop()

    for pos in snake_list:
        pygame.draw.rect(dis, green, pygame.Rect(pos[0], pos[1], snake_block, snake_block))


def time_and_score():
    # 渲染分数
    score_text = font.render("Score: " + str(score), True, (255, 255, 255))
    # 绘制分数
    dis.blit(score_text, (10, 10))


# 游戏主循环
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                snake_dir = 'UP'
            if event.key == pygame.K_DOWN:
                snake_dir = 'DOWN'
            if event.key == pygame.K_LEFT:
                snake_dir = 'LEFT'
            if event.key == pygame.K_RIGHT:
                snake_dir = 'RIGHT'

    # 更新蛇的位置
    if snake_dir == 'UP':
        snake_pos.insert(0, [snake_pos[0][0], snake_pos[0][1] - 10])
    if snake_dir == 'DOWN':
        snake_pos.insert(0, [snake_pos[0][0], snake_pos[0][1] + 10])
    if snake_dir == 'LEFT':
        snake_pos.insert(0, [snake_pos[0][0] - 10, snake_pos[0][1]])
    if snake_dir == 'RIGHT':
        snake_pos.insert(0, [snake_pos[0][0] + 10, snake_pos[0][1]])

    # 如果蛇吃到食物
    if snake_pos[0][0] == food_pos[0] and snake_pos[0][1] == food_pos[1]:
        score += 1
        food_pos = [random.randrange(1, (dis_width // 10)) * 10,
                    random.randrange(1, (dis_height // 10)) * 10]
        snake_pos.append(snake_pos[-1])  # 增加蛇的长度

    # 清空屏幕并重新绘制
    dis.fill(black)
    snake(snake_block, snake_pos)
    pygame.draw.rect(dis, white, pygame.Rect(food_pos[0], food_pos[1], snake_block, snake_block))
    time_and_score()

    # 检查碰撞
    if snake_pos[0][0] >= dis_width or snake_pos[0][0] < 0:
        game_over()
    if snake_pos[0][1] >= dis_height or snake_pos[0][1] < 0:
        game_over()

    # 更新显示
    pygame.display.update()

    # 控制游戏速度
    clock.tick(10)
